package org.dg.iag.server;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;

import org.dg.iag.dao.GenericDAO;
import org.dg.iag.query.XQueryGet;
import org.dg.iag.query.XQueryUtil;
import org.dg.iag.util.ApplicationConstants;
import org.dg.iag.util.RestletUtil;
import org.restlet.data.Form;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;

import com.thoughtworks.xstream.io.copy.HierarchicalStreamCopier;
import com.thoughtworks.xstream.io.json.JsonWriter;
import com.thoughtworks.xstream.io.xml.XppReader;

public class ActionsServerResource extends ServerResource {
	
	@Get
	public Object getActivity() {
		HashMap<String, String> params	= new HashMap<String, String>();
		
		
		RestletUtil.populateParamsMap(params, getRequest() );
		
		XQueryGet xqg;
		GenericDAO<Object, Object> gdao	= new GenericDAO<Object, Object>(ApplicationConstants.IATI_STORAGE_PATH);
		String format					= params.remove("format");
		if ( params.size() > 0 ) {
			//XQueryGet xqg					= new XQueryGet("", "/iati-activities/iati-activity[iati-identifier='"+params.get("iati-identifier")+"']", false);
			
			xqg		= new XQueryGet("", "for $item in /iati-activities/iati-activity" + XQueryUtil.generateXpathCondition(params, true) +
					" order by $item/title/text() return  <item><id>{$item/iati-identifier/text()}</id><label>{$item/title/text()}</label></item>", 
					true, false);
		}
		else {
			xqg		= new XQueryGet("", "for $item in /iati-activities/iati-activity" +
					" order by $item/title/text() return  <item><id>{$item/iati-identifier/text()}</id><label>{$item/title/text()}</label></item>", 
					true, false);
		}
		String start 	= (String)this.getRequest().getAttributes().get("start");
		if (start != null) {
			try {
				xqg.setStart(Integer.parseInt(start));
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}
		String howmany 	= (String)this.getRequest().getAttributes().get("howmany");
		if (howmany != null) {
			try {
				xqg.setHowmany(Integer.parseInt(howmany));
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}
		
		String ret						= gdao.getElementsAsString(xqg);
//			StringBuilder sb				= new StringBuilder( 2*"</results>".length() + ret.length() );
//			sb.append("<results>").append(ret).append("</results>");
//			ret								= sb.toString();
		
		if ( format != null && "json".equals( format ) ) {
			ret		= RestletUtil.generateJsonFromXML(ret);
		}
		
		
			return ret;
	}
}
